<template>
  <div class="container">
    <!-- 主体三列布局 -->
    <div class="main-container">
      <!-- 左侧广告以弹窗形式显示，不占据布局空间 -->
      <div class="ad-modal" v-if="showAdPopup">
        <button class="ad-close" @click="closeAdPopup">×</button>
        <button
          class="mute-control"
          v-if="adData && adData.resource_type === '1'"
          @click="toggleMute"
        >
          广告
          <img
            src="@/assets/detail/静音@2x.png"
            alt=""
            srcset=""
            v-if="isMuted"
          />
          <img src="@/assets/detail/有音@2x.png" alt="" srcset="" v-else />
        </button>
        <div class="ad-container">
          <!-- 加载状态 -->
          <div class="ad-loading" v-if="!adLoaded">
            <div class="loading-spinner"></div>
            <p class="loading-text">{{ $t("common.loading") }}</p>
          </div>
          
          <!-- 广告内容 -->
          <template v-else-if="adData">
            <template v-if="adData.link">
              <a :href="adData.link" target="_blank" class="ad-link">
                <template v-if="adData.resource_type === '2'">
                  <img
                    :src="adData.path"
                    :alt="adData.title || '广告图片'"
                    class="ad-media"
                    @error="handleAdError"
                  />
                </template>
                <template v-else-if="adData.resource_type === '1'">
                  <video
                    :src="adData.path"
                    class="ad-media"
                    autoplay
                    loop
                    controls
                    :muted="isMuted"
                    @error="handleAdError"
                    ref="adVideo"
                  ></video>
                </template>
              </a>
            </template>
            <template v-else>
              <template v-if="adData.resource_type === '2'">
                <img
                  :src="adData.path"
                  :alt="adData.title || '广告图片'"
                  class="ad-media"
                  @error="handleAdError"
                />
              </template>
              <template v-else-if="adData.resource_type === '1'">
                <video
                  :src="adData.path"
                  class="ad-media"
                  autoplay
                  loop
                  controls
                  :muted="isMuted"
                  @error="handleAdError"
                  ref="adVideo"
                ></video>
              </template>
            </template>
          </template>
          
          <!-- 占位符状态 -->
          <div class="ad-placeholder" v-else>
            <span>{{ $t("common.adPlaceholder") }}</span>
          </div>
        </div>
      </div>

      <!-- 中间图表区 -->
      <main class="center-content">
        <!-- 图表标题与选择器 -->
        <div class="chart-header">
          <div class="coin-title">
            <h2>{{ selectedCoin?.name || $t("common.selectCrypto") }}</h2>
            <button
              class="favorite-toggle"
              @click="toggleFavorite(selectedCoin)"
              :class="{ active: isFavorite(selectedCoin?.id) }"
            >
              <img
                src="@/assets/detail/关注-已关注@2x.png"
                alt=""
                srcset=""
                v-if="isFavorite(selectedCoin?.id)"
              />
              <img
                src="@/assets/detail/关注-未关注@2x.png"
                alt=""
                srcset=""
                v-else
              />
              {{
                isFavorite(selectedCoin?.id)
                  ? $t("common.favorited")
                  : $t("common.favorite")
              }}
            </button>
            <button
              class="favorite-toggle"
              @click="handleShare(selectedCoin)"
              :class="{ active: isFavorite(selectedCoin?.id) }"
            >
              <img src="@/assets/detail/分享@2x.png" alt="" srcset="" />
              {{ $t("common.share") }}
            </button>
          </div>
          <div class="time-selector">
            <button
              v-for="(period, key) in $t('timePeriods', { returnObject: true })"
              :key="key"
              @click="changeTimePeriod(key)"
              :class="{ active: activeTimePeriod === key }"
            >
              {{ period }}
            </button>
          </div>
        </div>

        <!-- K线图表 -->
        <div class="chart-container" ref="chartContainer">
          <TradingVue
            v-if="chartData.chart.data.length > 0"
            title-txt="trading"
            :toolbar="false"
            :data="chartData"
            :width="1160"
            :height="780"
          />
          <div v-else class="chart-loading">
            {{ $t("common.loadingChart") }}
          </div>
        </div>
      </main>

      <!-- 右侧关注列表 -->
      <aside class="right-sidebar">
        <!-- 头部：标题 + 搜索框 -->
        <div class="favorites-header">
          <h3>{{ $t("common.favorites") }}</h3>
          <!-- 新增搜索框 -->
          <div class="favorites-search">
            <svg
              class="search-icon"
              xmlns="http://www.w3.org/2000/svg"
              width="16"
              height="16"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
            >
              <circle cx="11" cy="11" r="8"></circle>
              <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
            </svg>
            <input
              type="text"
              v-model="favoriteSearchQuery"
              :placeholder="$t('common.searchPlaceholder')"
              @input="filterFavorites"
              class="search-input"
            />
          </div>
        </div>
        <!-- 收藏列表 -->
        <div class="favorites-list">
          <div
            class="favorite-item"
            v-for="coin in filteredFavoriteCoins"
            :key="coin.id"
            @click="selectCoin(coin)"
          >
            <!-- 币种信息 -->
            <div class="favorite-left">
              <img :src="coin.image" :alt="coin.name" class="favorite-logo" />
              <div class="favorite-name-wrap">
                <span class="favorite-symbol">{{
                  coin.symbol?.toUpperCase()
                }}</span>
              </div>
              <div
                class="favorite-change"
                :class="{
                  up: coin.price_change_percentage_24h > 0,
                  down: coin.price_change_percentage_24h < 0,
                }"
              >
                <span
                  v-if="coin.price_change_percentage_24h > 0"
                  class="trend-icon"
                  >↗</span
                >
                <span
                  v-else-if="coin.price_change_percentage_24h < 0"
                  class="trend-icon"
                  >↘</span
                >
                {{ coin.price_change_percentage_24h | numberFormat(1) }}%
              </div>
            </div>

            <!-- 涨幅 + 价格 -->
            <div class="favorite-right">
              <div class="favorite-price">
                {{ getCurrency === "cny" ? "¥" : "$"
                }}{{ coin.current_price | numberFormat(1) }}
              </div>
              <!-- 取消关注按钮 -->
              <button
                class="remove-favorite"
                @click.stop="removeFavorite(coin.id)"
              >
                {{ $t("common.remove") }}
              </button>
            </div>
          </div>

          <!-- 空状态 -->
          <div class="empty-state" v-if="filteredFavoriteCoins.length === 0">
            <p style="font-size: 16px; color: #6c6a69">
              {{ $t("common.noFavorites") }}
            </p>
            <p style="font-size: 14px; color: #999695">
              {{ $t("common.addToFavorites") }}
            </p>
          </div>
        </div>
      </aside>
    </div>
  </div>
</template>

<script>
import TradingVue from "trading-vue-js";
import axios from "axios";
import { mapGetters } from "vuex";

import Data from "./data.json";

// 配置axios
axios.defaults.headers.common = {
  "x-cg-demo-api-key": "CG-NbjxFryfS8oFS1PBbJbjj35Z",
};

export default {
  components: { TradingVue },
  data() {
    return {
      adData: null, // 广告数据
      isMuted: true, // 视频是否静音
      adLoaded: false, // 广告是否加载完成
      showAdPopup: true, // 显示广告弹窗
      adCloseTimer: null, // 弹窗自动关闭定时器

      favoriteSearchQuery: "",

      // 分页配置
      currentPage: 1,
      itemsPerPage: 10,
      totalPages: 0,
      shareText: this.$t("common.share"),
      // 行情滚动条
      tickerData: [],
      combinedTickerData: [], // 新增：用于无缝滚动的重复数据
      tickerPosition: 0,
      tickerInterval: null,
      tickerWidth: 180, // 单个ticker-item的宽度（包含间距）

      // 选中币种
      selectedCoin: null,

      // 时间周期
      timePeriods: {
        "1h": "1小时",
        "4h": "4小时",
        "1d": "1天",
        "1w": "1周",
        "1m": "1月",
      },
      activeTimePeriod: "1d",
      chat: Data,
      // 图表数据
      chartData: {
        chart: {
          type: "Candles",
          data: [],
        },
        onchart: [],
        offchart: [],
      },
      // 收藏列表
      favoriteCoins: [],
      // 图表宽度
      chartWidth: 860,
    };
  },
  filters: {
    numberFormat(value, decimals = 2) {
      if (!value && value !== 0) return "0";
      return value.toFixed(decimals).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    },
  },
  computed: {
    ...mapGetters(["getCurrency"]),
    // 分页数据
    paginatedCoins() {
      const startIndex = (this.currentPage - 1) * this.itemsPerPage;
      return this.filteredCoins.slice(
        startIndex,
        startIndex + this.itemsPerPage
      );
    },
    // 新增：过滤后的收藏列表
    filteredFavoriteCoins() {
      if (!this.favoriteSearchQuery.trim()) {
        return this.favoriteCoins; // 无搜索词时显示全部
      }
      const query = this.favoriteSearchQuery.toLowerCase();
      return this.favoriteCoins.filter(
        (coin) =>
          coin.name.toLowerCase().includes(query) ||
          coin.symbol.toLowerCase().includes(query)
      );
    },
  },
  watch: {
    // 筛选结果变化时重置分页
    filteredCoins() {
      this.totalPages = Math.ceil(
        this.filteredCoins.length / this.itemsPerPage
      );
      if (this.currentPage > this.totalPages) {
        this.currentPage = Math.max(1, this.totalPages);
      }
    },

    // 时间周期变化时重新加载图表
    activeTimePeriod() {
      if (this.selectedCoin) {
        this.loadChartData(this.selectedCoin.id);
      }
    },

    // 监听收藏列表变化并保存到本地存储
    favoriteCoins: {
      deep: true,
      handler() {
        localStorage.setItem(
          "cryptoFavorites",
          JSON.stringify(this.favoriteCoins)
        );
      },
    },
    getCurrency() {
      this.loadChartData(this.coinId);
      this.loadFavoritesFromStorage();
    },
  },
  mounted() {
    // 初始化数据
    const coin = JSON.parse(this.$route.query.coin);
    const id = this.$route.params.id;
    this.coinId = id;
    console.log("🚀 ~ mounted ~ id:", id, coin.id);
    if (id && coin) {
      this.selectedCoin = coin;
      this.loadChartData(id);
    }

    // 从本地存储加载收藏
    this.loadFavoritesFromStorage();

    // 订阅事件
    this.$eventBus.$on("topSearchCoin", this.selectSearchResult);
    this.fetchAdData();

    // 弹窗5秒后自动关闭
    this.adCloseTimer = setTimeout(() => {
      this.showAdPopup = false;
      // this.updateChartWidth();
    }, 5000);

    // 初始化并监听窗口尺寸变化，更新图表宽度
    // this.$nextTick(() => {
    //   this.updateChartWidth();
    //   window.addEventListener("resize", this.updateChartWidth);
    // });
  },
  beforeDestroy() {
    // 清除定时器
    if (this.tickerInterval) {
      clearInterval(this.tickerInterval);
    }
    // 订阅事件
    this.$eventBus.$off("topSearchCoin");

    if (this.adCloseTimer) {
      clearTimeout(this.adCloseTimer);
    }
    // window.removeEventListener("resize", this.updateChartWidth);
  },
  methods: {
    // 获取广告数据
    async fetchAdData() {
      try {
        // 开始加载，显示加载动画
        this.adLoaded = false;
        
        const response = await axios.get(
          "http://47.83.150.5:2027/api/v1/coins/advertise"
        );
        if (response.data && response.data.data) {
          this.adData = response.data.data;

        }
        // 数据加载完成，隐藏加载动画
        this.adLoaded = true;
      } catch (error) {
        console.error("加载广告数据失败:", error);
        // 即使加载失败也要隐藏加载动画
        this.adLoaded = true;
      }
    },
    closeAdPopup() {
      this.showAdPopup = false;
      if (this.adCloseTimer) clearTimeout(this.adCloseTimer);
      // this.updateChartWidth();
    },
    updateChartWidth() {
      const container = this.$refs.chartContainer;
      if (!container) return;
      // 预留右侧边距以及与右侧栏间距
      const rightSidebarWidth = 387;
      const gapWidth = 40;
      const maxAvailable = container.parentElement.clientWidth - 80;
      // TradingVue expects number width
      // 无论弹窗是否显示，都使用相同的宽度计算逻辑，避免抖动
      this.chartWidth = Math.max(600, maxAvailable);
    },

    // 切换静音状态
    toggleMute() {
      this.isMuted = !this.isMuted;
      if (this.$refs.adVideo) {
        this.$refs.adVideo.muted = this.isMuted;
      }
    },

    // 处理广告加载错误
    handleAdError() {
      console.error("广告资源加载失败");
      this.adData = null; // 显示占位符
    },
    filterFavorites() {
      // 依赖computed自动过滤，无需额外逻辑，保留方法占位
    },
    // 搜索处理
    handleSearch() {
      const query = this.searchQuery.toLowerCase().trim();
      if (!query) {
        this.filteredCoins = [...this.allCoins];
        this.filteredSearchResults = [];
        return;
      }

      // 过滤结果同时用于列表和下拉框
      const results = this.allCoins.filter(
        (coin) =>
          coin.name.toLowerCase().includes(query) ||
          coin.symbol.toLowerCase().includes(query)
      );

      this.filteredCoins = results;
      // 下拉列表最多显示10项
      this.filteredSearchResults = results.slice(0, 10);
      this.showDropdown = true;
    },

    // 选择币种
    selectCoin(coin) {
      this.selectedCoin = coin;
      this.loadChartData(coin.id);
    },

    // 加载图表数据
    async loadChartData(coinId) {
      try {
        const header = {
          headers: {
            vs_currency: this.getCurrency, // 自定义头
          },
        };
        // 根据时间周期转换为天数
        const daysMap = {
          "1h": 1, // 1天数据但按小时展示
          "4h": 7, // 7天数据按4小时展示
          "1d": 30, // 30天数据按天展示
          "1w": 90, // 90天数据按周展示
          "1m": 365, // 365天数据按月展示
        };

        // const response = await axios.get(
        //   `http://47.83.150.5:2027/api/v1/coins/${coinId}/ohlc?vs_currency=usd&days=${daysMap[this.activeTimePeriod]}`,
        //   {...header}
        // )

        const response = await axios.get(
          `http://47.83.150.5:2027/api/v1/coins/history_data?id=${coinId}&days=${
            daysMap[this.activeTimePeriod]
          }`,
          { ...header }
        );
        console.log("🚀 ~ loadChartData ~ response:", response);
        // 2. 格式化K线数据
        const ohlcvData = response.data.data.map((item) => [
          item[0], // 时间戳（毫秒）
          item[1], // 开盘价
          item[2], // 最高价
          item[3], // 最低价
          item[4], // 收盘价（关键：用于计算RSI）
          item[5], // 成交量
        ]);

        // 3. 从OHLC数据中提取收盘价，计算RSI（周期14）
        const closes = ohlcvData.map((item) => item[4]); // 提取所有收盘价
        const rsiData = this.calculateRSI(closes, 14); // 计算RSI

        // 格式化K线数据，完全匹配data.json的结构
        this.chartData = {
          chart: {
            type: "Candles",
            data: ohlcvData,
          },
          // 保留原data.json中的其他图表配置（如需要可添加）
          onchart: [
            // {
            //   "name": "Trades",
            //   "type": "PerfectTrades",
            //   "data": [
            //     [
            //       1552550400000,
            //       1,
            //       3935.4046923289475
            //     ],
            //     [
            //       1552608000000,
            //       0,
            //       3957.1187319773358
            //     ]
            //   ],
            //   "settings": {
            //     "z-index": 5
            //   }
            // }
          ],
          offchart: [
            {
              name: "RSI",
              type: "RSI",
              data: ohlcvData.map((item, index) => [
                item[0], // 时间戳（与K线完全一致）
                rsiData[index] || null, // RSI值（不足时为null）
              ]),
              settings: {
                upper: 70,
                lower: 30,
              },
            },
          ],
        };
      } catch (error) {
        console.error("加载图表数据失败:", error);
      }
    },

    // 核心：计算RSI指标的函数（周期通常为14）
    calculateRSI(closes, period = 14) {
      if (closes.length < period + 1) {
        return Array(closes.length).fill(null); // 数据不足时返回空值
      }

      // 1. 计算价格变动（涨跌幅）
      const changes = [];
      for (let i = 1; i < closes.length; i++) {
        changes.push(closes[i] - closes[i - 1]);
      }

      // 2. 计算平均上涨和平均下跌
      let gains = [];
      let losses = [];
      changes.forEach((change) => {
        if (change > 0) {
          gains.push(change);
          losses.push(0);
        } else {
          gains.push(0);
          losses.push(Math.abs(change));
        }
      });

      // 3. 初始平均（前period个数据）
      let avgGain = gains.slice(0, period).reduce((a, b) => a + b, 0) / period;
      let avgLoss = losses.slice(0, period).reduce((a, b) => a + b, 0) / period;

      // 4. 计算RSI
      const rsi = [];
      // 前period个数据不足以计算RSI，填充null
      for (let i = 0; i < period; i++) {
        rsi.push(null);
      }

      // 从第period+1个数据开始计算
      rsi.push(100 - 100 / (1 + avgGain / avgLoss));

      // 后续数据使用平滑平均
      for (let i = period + 1; i < closes.length; i++) {
        const currentGain = gains[i - 1];
        const currentLoss = losses[i - 1];

        // 平滑计算：(前平均 * (period-1) + 当前变动) / period
        avgGain = (avgGain * (period - 1) + currentGain) / period;
        avgLoss = (avgLoss * (period - 1) + currentLoss) / period;

        const rs = avgGain / avgLoss;
        rsi.push(100 - 100 / (1 + rs));
      }

      return rsi;
    },

    // 切换时间周期
    changeTimePeriod(period) {
      this.activeTimePeriod = period;
    },

    // 分页控制
    changePage(page) {
      if (page < 1 || page > this.totalPages) return;
      this.currentPage = page;
      window.scrollTo({ top: 0, behavior: "smooth" });
    },
    toggleFavorite(coin) {
      if (!coin) return;
      const isFavorite = this.isFavorite(coin.id);
      if (isFavorite) {
        this.removeFavorite(coin.id);
      } else {
        this.addFavorite(coin);
      }
    },
    isFavorite(coinId) {
      return this.favoriteCoins.some((coin) => coin.id === coinId);
    },
    // 滚动动画 - 关键修改
    startTickerAnimation() {
      const tickerSpeed = 2; // 滚动速度
      const resetPosition = -this.tickerData.length * this.tickerWidth; // 重置位置

      this.tickerInterval = setInterval(() => {
        this.tickerPosition -= tickerSpeed;

        // 关键修改：当滚动完第一组数据后，无缝重置到起始位置
        if (this.tickerPosition <= resetPosition) {
          this.tickerPosition = 0; // 重置到起点，因为第二组数据与第一组相同，视觉上无间断
        }
      }, 50);
    },

    // 加载本地存储的收藏
   async  loadFavoritesFromStorage() {
      const stored = localStorage.getItem("cryptoFavorites");
      const storeJson = JSON.parse(stored);
      if (storeJson && storeJson.length > 0) {
        try {
          const header = {
            headers: {
              vs_currency: this.getCurrency, // 自定义头
            },
          };
          const response = await axios.get(
            `http://47.83.150.5:2027/api/v1/coins/market_data?ids=${storeJson.map(coin => coin.id).join(",")}`,
            { ...header }
          );
          
          this.favoriteCoins = response.data?.data ?? [];
          console.log("🚀 ~ loadFavoritesFromStorage ~ this.favoriteCoins:", this.favoriteCoins)
        } catch (error) {
           this.favoriteCoins = storeJson;
        }
      }

    },

    // 切换收藏状态
    toggleFavorite(coin) {
      const isFavorite = this.isFavorite(coin.id);

      if (isFavorite) {
        this.removeFavorite(coin.id);
      } else {
        this.addFavorite(coin);
      }
    },

    // 添加到收藏
    addFavorite(coin) {
      console.log("🚀 ~ addFavorite ~ coin:", coin, this.getCurrency);

      // 只保留必要字段
      const favoriteCoin = {
        id: coin.id,
        name: coin.name,
        symbol: coin.symbol,
        image: coin.image,
        high_24h: coin.high_24h,
        low_24h: coin.low_24h,
        price_change_percentage_24h: coin.price_change_percentage_24h,
        market_cap: coin.market_cap,
        current_price: coin.current_price,
      };

      this.favoriteCoins.push(favoriteCoin);
    },

    // 从收藏中移除
    removeFavorite(coinId) {
      this.favoriteCoins = this.favoriteCoins.filter(
        (coin) => coin.id !== coinId
      );
    },

    // 检查是否为收藏
    isFavorite(coinId) {
      return this.favoriteCoins.some((coin) => coin.id === coinId);
    },

    // 新增：选择搜索结果
    selectSearchResult(coin) {
      this.selectCoin(coin);
      this.searchQuery = "";
      this.showDropdown = false;
    },
    // 修正方法名拼写错误并实现分享功能
    async handleShare(coin) {
      if (!coin) {
        this.showToast(this.$t("common.pleaseSelectCoin"));
        return;
      }

      // 构建分享链接（使用当前页面URL）
      const shareUrl = `${window.location.origin}/coin/${
        coin.id
      }?coin=${encodeURIComponent(JSON.stringify(coin))}`;
      const shareText = this.$t("common.shareText", {
        name: coin.name,
        symbol: coin.symbol.toUpperCase(),
      });

      try {
        // 尝试使用Web Share API（支持现代浏览器和移动设备）
        if (navigator.share) {
          await navigator.share({
            title: `${coin.name} (${coin.symbol.toUpperCase()})`,
            text: shareText,
            url: shareUrl,
          });
          this.showToast(this.$t("common.shareSuccess"));
        } else {
          // 不支持Web Share API时， fallback到复制链接
          await navigator.clipboard.writeText(shareUrl);
          this.showToast(this.$t("common.linkCopied"));
        }
      } catch (error) {
        console.error("分享失败:", error);
        // 复制链接失败时的备选方案（创建临时输入框）
        if (error.name !== "AbortError") {
          this.fallbackCopyText(shareUrl);
        }
      }
    },

    // 复制链接的备选方案（当Clipboard API不可用时）
    fallbackCopyText(text) {
      const textarea = document.createElement("textarea");
      textarea.value = text;
      textarea.style.position = "fixed";
      document.body.appendChild(textarea);
      textarea.select();

      try {
        const successful = document.execCommand("copy");
        this.showToast(
          successful
            ? this.$t("common.linkCopied")
            : this.$t("common.copyFailed")
        );
      } catch (err) {
        console.error("Fallback copy failed:", err);
        this.showToast(this.$t("common.copyFailed"));
      } finally {
        document.body.removeChild(textarea);
      }
    },

    // 简单的提示消息方法（可根据项目实际UI组件替换）
    showToast(message) {
      // 这里使用浏览器默认alert作为示例
      // 实际项目中建议替换为Element UI、Vuetify等的通知组件
      alert(message);
    },
  },
};
</script>

<style scoped lang="scss">
/* 全局样式 */
.container {
  font-family: "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
  color: #1e293b;
}

/* 弹窗样式：固定在页面中央，完全脱离文档流 */
.ad-modal {
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 260px;
  height: 420px;
  background: #ffffff;
  /* 使用filter阴影替代box-shadow，避免影响页面布局 */
  filter: drop-shadow(0px 2px 10px rgba(0, 0, 0, 0.15));
  border-radius: 8px;
  z-index: 1000;
  overflow: hidden;
  /* 确保弹窗完全不影响页面布局 */
  pointer-events: auto;
  contain: layout style paint;
  /* 防止影响页面滚动条 */
  isolation: isolate;
}

.ad-close {
  position: absolute;
  top: 6px;
  right: 8px;
  background: rgba(0, 0, 0, 0.5);
  color: #fff;
  border: none;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  cursor: pointer;
  z-index: 11;
}

/* 顶部区域 */
.top-section {
  background-color: #ffffff;
  border-bottom: 1px solid #e2e8f0;
  padding: 1rem 2rem;
}

/* 搜索栏 */
.search-container {
  display: flex;
  max-width: 600px;
  margin: 0 auto 1rem;
  position: relative;
}

.search-btn {
  background-color: #3b82f6;
  color: white;
  border: none;
  padding: 0 1rem;
  border-radius: 0 8px 8px 0;
  cursor: pointer;
  transition: background-color 0.2s;
}

.search-btn:hover {
  background-color: #2563eb;
}

/* 行情滚动条 */
.ticker-container {
  background-color: #0f172a;
  color: white;
  /* padding: 0rem 0.5rem; */
  overflow: hidden;
  position: relative;
  white-space: nowrap;
  height: 30px;
  border-radius: 4px;
  max-width: 1800px;
  /* 限制最大宽度为1800px */
  margin: 0 auto;
  /* 水平居中 */
}

.ticker-track {
  display: flex;
  position: absolute;
  gap: 2rem;
  top: 4px;
}

.ticker-item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  min-width: max-content;
}

/* 新增币种图标样式 */
.ticker-icon {
  width: 18px;
  height: 18px;
  border-radius: 50%;
  object-fit: cover;
}

.ticker-symbol {
  font-weight: 600;
  margin-left: 0rem;
  /* 调整与图标的间距 */
}

.ticker-up {
  color: #22c55e;
}

.ticker-down {
  color: #ef4444;
}

/* 主体三列布局 */
.main-container {
  display: flex;
  gap: 40px;
  max-width: 1670px; /* 改为最大宽度 */
  width: 100%; /* 占满可用宽度 */
  margin: 0 auto;
  box-sizing: border-box;
  /* 防止弹窗显示/隐藏时的布局抖动 */
  contain: layout;
  will-change: auto;
}

/* 移除左侧栏占位（保留原样式以避免大范围改动） */
.left-sidebar {
  display: none;
}

/* 中间图表区 */
.center-content {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
  background-color: #ffffff;
  box-shadow: 0px 2px 10px 0px rgba(0, 0, 0, 0.05);
  border-radius: 22px;
  padding: 32px 40px;
  flex: 1; /* 自动撑大 */
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-header h2 {
  margin: 0;
  font-size: 1.5rem;
  color: #1e293b;
}

.time-selector {
  display: flex;
  gap: 0.5rem;
}

.time-selector button {
  background-color: #ffffff;
  border: 1px solid #e2e8f0;
  padding: 0.2rem 0.6rem;
  border-radius: 6px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: all 0.2s;
}

.time-selector button.active {
  background-color: #3b82f6;
  color: white;
  border-color: #3b82f6;
}

.chart-container {
  height: 780px;
  width: 100%; /* 改为 100% 适应父容器 */
  /* 移除最大宽度限制以便自动撑大 */
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 12px;
  overflow: hidden;
}
.chart-loading {
  color: #64748b;
  font-size: 1.1rem;
}

/* 统计数据栏 */
.stats-bar {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 1rem;
}

.stat-item {
  background-color: #ffffff;
  border-radius: 8px;
  padding: 1rem;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.stat-label {
  color: #64748b;
  font-size: 0.9rem;
  margin-bottom: 0.5rem;
  display: block;
}

.stat-value {
  font-size: 1.25rem;
  font-weight: 600;
}

/* 右侧收藏区 */
.right-sidebar {
  width: 387px;
  height: 920px;
  background-color: #ffffff;
  border-radius: 22px; /* 匹配整体卡片圆角 */
  padding: 34px 0px;
  box-shadow: 0px 2px 10px 0px rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  box-sizing: border-box; /* 确保padding不影响宽高 */
}

.favorites-header {
  margin-bottom: 1rem;
  padding: 0 32px;
}

.favorites-header h3 {
  margin: 0 0 0.5rem 0;
  font-size: 18px;
}

.storage-info {
  font-size: 0.8rem;
  color: #64748b;
}

.favorites-list {
  flex: 1;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
}

.favorite-logo {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  // margin-right: 0.75rem;
}

.favorite-info {
  flex: 1;
}

.favorite-name {
  font-weight: 500;
  margin-bottom: 0.25rem;
}

.favorite-symbol {
  font-size: 0.8rem;
  color: #64748b;
  margin-left: 0.5rem;
}

.favorite-price {
  font-size: 0.9rem;
  color: #1e293b;
}

.remove-favorite {
  background: none;
  border: none;
  color: #64748b;
  cursor: pointer;
  padding: 0.25rem;
  border-radius: 4px;
  transition: color 0.2s;
}

// .remove-favorite:hover {
//   color: #ef4444;
//   background-color: rgba(239, 68, 68, 0.1);
// }

.empty-state {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #64748b;
  gap: 0.5rem;
}

/* 底部币种列表 */
.coins-table-section {
  padding: 0 2rem 2rem;
  max-width: 1800px;
  margin: 0 auto;
  width: 100%;
  box-sizing: border-box;
}

.coins-table {
  width: 100%;
  border-collapse: collapse;
  background-color: #ffffff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  margin-bottom: 1.5rem;
}

.coins-table th,
.coins-table td {
  padding: 1rem;
  text-align: left;
  border-bottom: 1px solid #e2e8f0;
}

.coins-table th {
  background-color: #f8fafc;
  color: #64748b;
  font-weight: 600;
  font-size: 0.9rem;
}

.coin-row {
  cursor: pointer;
  transition: background-color 0.2s;
}

.coin-row:hover {
  background-color: #f8fafc;
}

.coin-logo {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  margin-right: 0.75rem;
}

.coin-name {
  display: inline-block;
  vertical-align: middle;
}

.coin-symbol {
  font-size: 0.8rem;
  color: #64748b;
  margin-left: 0.5rem;
}

.up {
  color: #22c55e;
}

.down {
  color: #ef4444;
}

.favorite-btn {
  background: none;
  border: 1px solid #e2e8f0;
  border-radius: 4px;
  padding: 0.25rem;
  cursor: pointer;
  color: #64748b;
  transition: all 0.2s;
}

.favorite-btn.active {
  color: #ef4444;
  border-color: #ef4444;
}

.favorite-btn:hover:not(.active) {
  border-color: #3b82f6;
  color: #3b82f6;
}

/* 分页 */
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 0.75rem;
}

.page-btn {
  background-color: #ffffff;
  border: 1px solid #e2e8f0;
  padding: 0.5rem 1rem;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;
}

.page-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-btn:hover:not(:disabled) {
  border-color: #3b82f6;
  color: #3b82f6;
}

.page-numbers {
  display: flex;
  gap: 0.25rem;
}

.page-numbers button {
  width: 36px;
  height: 36px;
  border-radius: 6px;
  border: 1px solid #e2e8f0;
  background-color: #ffffff;
  cursor: pointer;
  transition: all 0.2s;
}

.page-numbers button.active {
  background-color: #3b82f6;
  color: white;
  border-color: #3b82f6;
}

.page-numbers button:hover:not(.active) {
  border-color: #3b82f6;
  color: #3b82f6;
}

/* 响应式设计 */
@media (max-width: 1400px) {
  .main-container {
    grid-template-columns: 240px 1fr 280px;
  }
}

@media (max-width: 1200px) {
  .main-container {
    grid-template-columns: 1fr;
  }

  .left-sidebar,
  .right-sidebar {
    display: none;
  }
}

@media (max-width: 768px) {
  .stats-bar {
    grid-template-columns: 1fr 1fr;
  }

  .coins-table th:nth-child(5),
  .coins-table td:nth-child(5) {
    display: none;
  }

  .search-container {
    max-width: 100%;
  }
}

@media (max-width: 480px) {
  .stats-bar {
    grid-template-columns: 1fr;
  }

  .time-selector {
    flex-wrap: wrap;
  }

  .coins-table th:nth-child(4),
  .coins-table td:nth-child(4) {
    display: none;
  }

  .top-section,
  .main-container,
  .coins-table-section {
    padding: 1rem;
  }
}

.coin-title {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.favorite-toggle {
  background-color: #3b82f6;
  color: white;
  border: none;
  padding: 0.2rem 0.5rem;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.2s;
  width: 90px;
  height: 38px;
  background: #f7f3f2;
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #6c6a69;

  img {
    width: 16px;
    height: 16px;
    margin-right: 4px;
  }
}

.favorite-toggle.active {
  // background-color: #ef4444;
}

.favorite-toggle:hover {
  // background-color: #2563eb;
}

/* 搜索下拉列表样式 */
.search-dropdown {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  margin-top: 4px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  z-index: 100;
  max-height: 360px;
  overflow-y: auto;
  border: 1px solid #e2e8f0;
}

/* 下拉列表项样式 */
.dropdown-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0.75rem 1rem;
  cursor: pointer;
  transition: background-color 0.2s;
}

.dropdown-item:hover {
  background-color: #f8fafc;
}

/* 下拉列表项内部元素样式 */
.dropdown-icon {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  margin-right: 0.75rem;
  object-fit: cover;
}

.dropdown-info {
  flex: 1;
}

.dropdown-name {
  font-weight: 500;
  margin-bottom: 2px;
}

.dropdown-symbol {
  font-size: 0.8rem;
  color: #64748b;
  margin-left: 0.5rem;
}

.dropdown-price {
  font-size: 0.85rem;
  color: #1e293b;
}

.dropdown-change {
  font-size: 0.85rem;
  font-weight: 500;
  min-width: 50px;
  text-align: right;
}

/* 下拉列表滚动条样式 */
.search-dropdown::-webkit-scrollbar {
  width: 6px;
}

.search-dropdown::-webkit-scrollbar-track {
  background: #f1f5f9;
  border-radius: 8px;
}

.search-dropdown::-webkit-scrollbar-thumb {
  background: #cbd5e1;
  border-radius: 8px;
}

.search-dropdown::-webkit-scrollbar-thumb:hover {
  background: #94a3b8;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .search-dropdown {
    left: 0;
    right: 0;
    width: 100%;
  }
}

/* 头部：标题 + 搜索框 */
.favorites-header {
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.favorites-header h3 {
  margin: 0;
  font-size: 18px;
  color: #1e293b;
  font-weight: 600;
}

/* 新增搜索框样式：匹配UI */
.favorites-search {
  position: relative;
  width: 100%;
}

.search-input {
  width: 100%;
  background: #f7f3f2;
  padding: 10px 16px 10px 36px; /* 给搜索图标留空间 */
  border: none;
  border-radius: 22px; /* 圆角输入框 */
  font-size: 14px;
  color: #333333;
  outline: none;
  box-sizing: border-box;
  transition: border-color 0.2s;
  height: 52px;
}

.search-input::placeholder {
  color: #999695;
  font-size: 14px;
}

.search-input:focus {
  border-color: #3b82f6;
}

.search-icon {
  position: absolute;
  left: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #999695;
  width: 16px;
  height: 16px;
}

/* 收藏列表：新增向下滚动 + 样式优化 */
.favorites-list {
  flex: 1; /* 占满剩余高度 */
  overflow-y: auto; /* 向下滚动（超出时显示垂直滚动条） */
  overflow-x: hidden; /* 隐藏水平滚动 */
  display: flex;
  flex-direction: column;
  // gap: 12px; /* 列表项间距 */
  padding-right: 4px; /* 避免滚动条遮挡内容 */
}

/* 列表项滚动条样式：美化 */
.favorites-list::-webkit-scrollbar {
  width: 6px;
}

.favorites-list::-webkit-scrollbar-track {
  background: #f7f7f7;
  border-radius: 3px;
}

.favorites-list::-webkit-scrollbar-thumb {
  background: #dcdcdc;
  border-radius: 3px;
}

.favorites-list::-webkit-scrollbar-thumb:hover {
  background: #cccccc;
}

/* 收藏列表项：匹配UI布局（左-图标名称 / 中-涨幅价格 / 右-取消关注） */
.favorite-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 32px;
  cursor: pointer;
  transition: background-color 0.2s;
  height: 80px;
  position: relative;
  &::after {
    content: "";
    position: absolute;
    width: 340px;
    height: 1px;
    background: #eeeeee;
    bottom: 0;
    left: 32px;
  }
}

.favorite-item:hover {
  // background-color: #F0F0F0;
  box-shadow: 0px 2px 10px 0px rgba(0, 0, 0, 0.05);
  .favorite-price {
    display: none;
  }
  .remove-favorite {
    display: block;
  }
}

/* 列表项左侧：图标 + 名称 */
.favorite-left {
  display: flex;
  align-items: center;
  gap: 0px;
}

.favorite-logo {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  object-fit: cover;
}

.favorite-name-wrap {
  display: flex;
  align-items: center;
}

.favorite-name {
  font-size: 16px;
  font-weight: 600;
  color: #302d2c;
}

.favorite-symbol {
  font-size: 16px;
  font-weight: 600;
  color: #302d2c;
}

/* 列表项中间：涨幅 + 价格 */
.favorite-right {
  display: flex;
  align-items: center;
}

.favorite-change {
  font-size: 16px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 4px;
  margin-left: 20px;
  color: #17a478;
  span {
    font-size: 8px;
  }
}

.trend-icon {
  font-size: 12px;
}

.favorite-change.up {
  color: #4caf50; /* 上涨绿色 */
}

.favorite-change.down {
  color: #f44336; /* 下跌红色 */
}

.favorite-price {
  font-size: 16px;
  color: #302d2c;
}

/* 取消关注按钮：匹配UI */
.remove-favorite {
  display: none;
  background: none;

  font-size: 16px;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.2s;
  margin-left: 8px;
  width: 87px;
  height: 32px;
  background: #ff722b;
  border-radius: 8px;
  color: white;
}

// .remove-favorite:hover {
//   background-color: #6C6A69;
//   color: white;
// }

/* 空状态：匹配UI样式 */
.empty-state {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 8px;
  color: #999695;
  padding: 40px 0;
}

/* 修复原有样式冲突（若有） */
.favorite-item .favorite-info {
  display: none; /* 隐藏原有info结构，替换为新布局 */
}

/* 广告容器样式 */
.ad-container {
  width: 260px;
  height: 420px;
  position: relative;
  margin: auto; /* 上下居中 */
  overflow: hidden;
  // border-radius: 8px;
  img,
  video {
    width: 260px;
    height: 420px;
  }
  img.ad-media {
    object-fit: fill;
  }
}

/* 加载动画样式 */
.ad-loading {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #f8f9fa;
  color: #6c757d;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #e9ecef;
  border-top: 4px solid #3b82f6;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

.loading-text {
  margin: 0;
  font-size: 14px;
  color: #6c757d;
  font-weight: 500;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 图片广告样式 */
.ad-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

/* 视频广告样式 */
.ad-video {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

/* 静音控制按钮 */
.mute-control {
  position: absolute;
  top: 24px;
  left: 24px;
  width: 87px;
  height: 41px;
  background: rgba(0, 0, 0, 0.3);
  border-radius: 10px;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
  transition: background-color 0.2s;
  gap: 10px;
  img {
    width: 17px;
    height: 15px;
  }
}

.mute-control:hover {
  background-color: rgba(0, 0, 0, 0.7);
}

/* 广告链接样式 */
.ad-link {
  display: block;
  width: 100%;
  height: 100%;
}
</style>
